from selenium import webdriver
from time import sleep
from random import random
from PIL import Image
import numpy as np
from selenium.webdriver import ActionChains


class BiliBiliSpider(object):
    def __init__(self):
        self.chrome = webdriver.Chrome(executable_path='C:\chromedriver.exe')

    def computeDistance(self,fullImagePath,sliceImagePath):
        fullImage = Image.open(fullImagePath)
        sliceImage = Image.open(sliceImagePath)
        data1 = fullImage.getchannel(0)
        data2 = sliceImage.getchannel(0)
        width, height = data1.size
        arr1 = np.array(data1.getdata()).reshape((width,height))
        arr2 = np.array(data2.getdata()).reshape((width,height))
        minusArr = arr1-arr2

        distance = width / 2
        for i in range(width):
            ls = list(minusArr[i,])
            length = len(ls)
            ##颜色差别小的点设为相同
            for j in range(length):
                if abs(ls[j]) < 5:
                    ls[j] = 0
            if length-ls.count(0)>20:
                distance = i
                print("移动距离:",distance)
                return distance

    def dragSlider(self,X):
        print('总距离',X)
        action_chains = ActionChains(self.chrome)
        dragElement=self.chrome.find_element_by_xpath("//div[@class='geetest_slider geetest_ready']/div[@class='geetest_slider_button']")
        ActionChains(self.chrome).click_and_hold(dragElement).perform()
        ActionChains(self.chrome).move_by_offset(X-7,0).perform()
        # result=self.get_path(X)
        # print(result)
        # print('轨迹之和',sum(result))
        # for i in result:
        #     ActionChains(self.chrome).move_by_offset(i,0).perform()
        # sleep(.5)
        ActionChains(self.chrome).release().perform()
        sleep(3)

    def get_path(self,distance):
        distance = distance - 7
        track = []
        v = 0
        while sum(track)<distance / 2:
            track.append(v)
            v = v+1
        while sum(track)<distance:
            track.append(v)
            v = v-1
        return track

    def get_distance(self,fullImagePath, sliceImagePath):
        # 阈值
        threshold = 200
        fullbg_Image = Image.open(fullImagePath)
        bg_Image = Image.open(sliceImagePath)
        ##255*153 pixl
        for i in range(60, bg_Image.size[0]):#255
            for j in range(bg_Image.size[1]):#153
                bg_pix = bg_Image.getpixel((i, j))
                fullbg_pix = fullbg_Image.getpixel((i, j))
                r = abs(bg_pix[0] - fullbg_pix[0])
                g = abs(bg_pix[1] - fullbg_pix[1])
                b = abs(bg_pix[2] - fullbg_pix[2])
                if r + g + b > threshold:
                    return i

    def getCaptcha(self):
        fullImagePath = "fullImge.png"
        sliceImagePath = "sliceImge.png"
        # 背景图
        js_fullImage_block = "document.getElementsByClassName('geetest_canvas_fullbg geetest_fade geetest_absolute')[0].style.display='block'"
        self.chrome.execute_script(js_fullImage_block)
        self.chrome.find_element_by_xpath("//a[@class='geetest_link']/div[1]/div/canvas").screenshot(fullImagePath)
        sleep(.5)
        # 缺口图
        js_fullImage_None = "document.getElementsByClassName('geetest_canvas_fullbg geetest_fade geetest_absolute')[0].style.display='None'"
        self.chrome.execute_script(js_fullImage_None)
        # 隐藏滑块
        sleep(.5)
        js_slider_None = "document.getElementsByClassName('geetest_canvas_slice geetest_absolute')[0].style.display='None'"
        self.chrome.execute_script(js_slider_None)
        self.chrome.find_element_by_xpath("//a[@class='geetest_link']/div[1]/div/canvas").screenshot(sliceImagePath)
        #显示滑块
        sleep(.5)
        js_slider_block = "document.getElementsByClassName('geetest_canvas_slice geetest_absolute')[0].style.display='block'"
        self.chrome.execute_script(js_slider_block)
        return (fullImagePath,sliceImagePath)

    def userPassword(self):
        self.chrome.find_element_by_xpath("//input[@id='login-username']").send_keys('111')
        self.chrome.find_element_by_xpath("//input[@id='login-passwd']").send_keys('111')
        self.chrome.find_element_by_xpath("//li[@class='btn-box']/a[1]").click()
        sleep(2)

    def run(self):
        self.chrome.get("https://passport.bilibili.com/login")
        trytimes = 1
        while trytimes:
            self.userPassword()
            print('第 %d 次尝试'%trytimes)
            fullImagePath,sliceImagePath = self.getCaptcha()
            # distance=self.computeDistance(fullImagePath,sliceImagePath)
            distance = self.get_distance(fullImagePath,sliceImagePath)
            self.dragSlider(distance)
            if self.chrome.current_url == "https://www.bilibili.com/":
                print('成功')
                break
            self.chrome.refresh()
            sleep(3)
            trytimes += 1
        # self.chrome.quit()
        
if __name__=='__main__':
    spider = BiliBiliSpider()
    spider.run()
